package com.siriuscloud.holidayreservation.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siriuscloud.holidayreservation.domain.Matter;
import com.siriuscloud.holidayreservation.domain.vo.MatterVo;
import com.siriuscloud.holidayreservation.mapper.MatterMapper;
import com.siriuscloud.holidayreservation.utils.MyPage;
import com.siriuscloud.holidayreservation.utils.MyPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MatterService {

    @Resource
    private MatterMapper matterMapper;

    // 获取所有事项
    public List<Matter> getAllByDepartmentId(Long departmentId, String name) {
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.eq("department_id", departmentId);
        return matterMapper.selectList(queryWrapper);
    }

    // 根据分页和name获取所有事项
    public MyPageVo<MatterVo> getAllByPage(MyPage myPage, String name, String departmentId) {
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<Matter>();
        queryWrapper.eq("department_id", departmentId);
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        List<MatterVo> records = matterMapper.getAllMatterByPage(myPage, name, departmentId);
        MyPageVo<MatterVo> myPageVo = new MyPageVo<>();
        myPageVo.setRecords(records);
        Integer total = matterMapper.selectCount(queryWrapper);
        myPageVo.setTotal(total);
        return myPageVo;
    }

    // 新增一个事项
    public Boolean create(Matter matter) throws Exception {
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department_id", matter.getDepartmentId());
        queryWrapper.eq("name", matter.getName());
        if (matterMapper.selectCount(queryWrapper) > 0) {
            throw new Exception("同一个部门下,事项名称不能重复。");
        }
        return matterMapper.insert(matter) > 0;
    }

    // 编辑一个事项
    public Boolean update(Matter matter) {
        return matterMapper.updateById(matter) > 0;
    }

    // 删除事项
    public Boolean delete(Long id) {
        return matterMapper.deleteById(id) > 0;
    }

    public Matter getById(String id) {
        return matterMapper.selectById(id);
    }
}
